import React, { createContext, useState } from "react";
import classNames from 'classnames'
import { MenuItemProps } from './menuItem'

export interface MenuProps {
  defaultIndex?: string;
  className?: string;
  mode?: 'horizontal' | 'vertical';
  style?: React.CSSProperties;
  afterSelect?: (selectedIndex: string) => void;
  children?: React.ReactNode;
  defaultOpenSubMenus?: string[]
}
// context
interface IMenuContext { 
  index: string;
  onSelect?: (selectedIndex: string) => void;
  mode?: 'horizontal' | 'vertical';
  defaultOpenSubMenus?: string[]
}
export const MenuContext = createContext<IMenuContext>({index: '0'})

const Menu: React.FC<MenuProps> = (props: MenuProps) => {
  const { defaultIndex, className, mode, style, afterSelect, children, defaultOpenSubMenus } = props
  const classes = classNames('menu', className, {
    [`menu-${mode}`]: mode
  })
  const [currentActive, setCurrentActive] = useState(defaultIndex)
  // conext value
  const passedContext: IMenuContext = {
    index: currentActive ? currentActive : '0',
    onSelect: (index: string) => {
      setCurrentActive(index)
      afterSelect && afterSelect(index)
    },
    mode,
    defaultOpenSubMenus
  }
  // render menuItem component
  const renderChild = React.Children.map(children, (child, i) => {
    const childElement = child as React.FunctionComponentElement<MenuItemProps>
    const { displayName } = childElement.type
    if(displayName === 'menuItem' || displayName === 'subMenu') {
      // when the children is menuItem(have displayName menuItem)
      // add the menuItem a prop index
      return React.cloneElement(childElement, { index: i + '' })
    } else {
      // when the children is not menuItem
      console.log('warn: Menu has a child which is not a MenuItem component')
    }
  })

  return (
    <ul className={classes} style={style} data-testid="test-menu">
      <MenuContext.Provider value={passedContext}>
        {renderChild}
      </MenuContext.Provider>
    </ul>
  )
}

Menu.defaultProps = {
  defaultIndex: '0',
  mode: 'horizontal',
  defaultOpenSubMenus: []
}

export default Menu